package com.sean.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sean.gulimall.product.service.CategoryBrandRelationService;
import com.sean.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sean.gulimall.common.utils.PageUtils;
import com.sean.gulimall.common.utils.Query;

import com.sean.gulimall.product.dao.CategoryDao;
import com.sean.gulimall.product.entity.CategoryEntity;
import com.sean.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    CategoryDao categoryDao;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;


    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
             categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());




        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO  1、检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);


        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(value = "catalog", allEntries = true) //保证缓存一致性：失效模式
//    @Caching(evict = {
//            @CacheEvict(value = "catalog", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "catalog", key = "'getCatalogJson'")
//    })
//    @CachePut//双写模式，但这个方法没有返回值 不能使用这个模式
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Cacheable(value = {"catalog"}, key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys...");
//        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
//        System.out.println("数据库查询时间："+(System.currentTimeMillis()-l));
        return categoryEntities;
    }

    @Cacheable(value = "catalog", key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        System.out.println("查询了数据库。。。");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //查出所有的1级分类
        List<CategoryEntity> level1Categorys = getParentCid(categoryEntities, 0L);
        //封装数据

        return level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每个一级分类的二级分类
            List<CategoryEntity> catalog2 = getParentCid(categoryEntities, v.getCatId());

            //2.封装结果
            List<Catalog2Vo> catalog2Vos = null;
            if (catalog2 != null) {
                catalog2Vos = catalog2.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //每一个二级分类的三级分类
                    List<CategoryEntity> catalog3s = getParentCid(categoryEntities, l2.getCatId());
                    //封装结果
                    List<Catalog2Vo.Catalog3> catalog3List = null;
                    if (catalog3s != null) {
                        catalog3List = catalog3s.stream().map(l3 -> {
                            return new Catalog2Vo.Catalog3(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3List);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
    }

    /*  产生堆外内存溢出
        1.sringboot2.0以后默认使用lettuce作为操作redis的客户端，它使用netty进行网络通信
        2.lettuce的bug导致netty堆外内存溢出
        解决办法：升级lettuce；   使用jedis代替lettuce
     */

    public Map<String, List<Catalog2Vo>> getCatalogJson2(){
        //注意需要序列化和反序列化  使用Json形式，可以跨语言、跨平台
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            System.out.println("缓存不命中。。。要查询数据库。。。");
            Map<String, List<Catalog2Vo>> catalogJsonFromDB = getCatalogJsonFromDBWithRedissonLock();
            //将对象转为Json形式，再保存到redis中
            String s = JSON.toJSONString(catalogJsonFromDB);
            redisTemplate.opsForValue().set("catalogJson", s);
            return catalogJsonFromDB;
        }
        System.out.println("缓存命中。。。直接返回。。。");
        //将redis夺取的数据转为真实对象 再返回
        return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
    }

    /**
     * 功能描述：使用redisson加锁 访问数据库拿数据
     *
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDBWithRedissonLock(){
        RLock lock = redisson.getLock("catalogJson-Lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> catalogJsonFromDB;
        try{
            catalogJsonFromDB = getCatalogJsonFromDB();
        }finally {
            lock.unlock();
        }
        return catalogJsonFromDB;
    }

    /**
     * 功能描述：从数据库中获取数据
     *
     */
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(!StringUtils.isEmpty(catalogJson)){
            return JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        }
        System.out.println("查询了数据库。。。");

        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //查出所有的1级分类
        List<CategoryEntity> level1Categorys = getParentCid(categoryEntities, 0L);

        //封装数据
        Map<String, List<Catalog2Vo>> collect = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1.每个一级分类的二级分类
            List<CategoryEntity> catalog2 = getParentCid(categoryEntities, v.getCatId());

            //2.封装结果
            List<Catalog2Vo> catalog2Vos = null;
            if (catalog2 != null) {
                catalog2Vos = catalog2.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //每一个二级分类的三级分类
                    List<CategoryEntity> catalog3s = getParentCid(categoryEntities, l2.getCatId());
                    //封装结果
                    List<Catalog2Vo.Catalog3> catalog3List = null;
                    if (catalog3s != null) {
                        catalog3List = catalog3s.stream().map(l3 -> {
                            Catalog2Vo.Catalog3 catalog3 = new Catalog2Vo.Catalog3(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3List);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return collect;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoryEntities, Long parentCid) {
        List<CategoryEntity> collect = categoryEntities.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());

        return collect;
    }

    //225,25,2
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2、菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }



}